import logging
import os
import time
from public.Tools import get_path


class Logger:

    def __init__(self, project_name, log_conf):
        logger = logging.getLogger(project_name)
        logger.setLevel(
            logging.DEBUG if log_conf['level'].lower() == 'high' else logging.INFO
        )

        log_path = get_path(f"logs/{project_name}")
        not os.path.exists(log_path) and os.mkdir(log_path)

        # logs/project_name/20230528.log
        # logs/project_name/now.log
        log_save_path = f"{log_path}/" + (time.strftime('%Y%m%d') if log_conf['daily'] else "now") + '.log'
        log_conf['clear'] and os.path.exists(log_save_path) and os.remove(log_save_path)

        sh = logging.StreamHandler()  # 定义输出到控制台的handler
        fh = logging.FileHandler(filename=log_save_path, encoding="utf-8")  # 定义输出到文件的handler
        formatter = logging.Formatter(f"%(asctime)s - {project_name} - %(levelname)s: %(message)s")  # 定义输出格式

        # 分别给两个handler设置格式
        sh.setFormatter(formatter)
        fh.setFormatter(formatter)

        # 最后将这两个handler设置到logger身上
        logger.addHandler(sh)
        logger.addHandler(fh)

        self.__logger = logger


    def debug(self, msg):
        self.__logger.debug(msg)

    def info(self, msg):
        self.__logger.info(msg)

    def error(self, msg):
        self.__logger.error(msg)